/**
 * 
 */
package es.aradesh.ministryassist.logic.ministry;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.provider.BaseColumns;

import es.aradesh.ministryassist.db.DbAdapter;
import es.aradesh.ministryassist.db.TerritoryColumns;

/**
 * @author xmorales
 * 
 */
public class TerritoryBuilder {
	/**
	 * Inserts a new Territory into the DB.
	 * 
	 * @param db
	 * @param name
	 * @param number
	 * @param town
	 * @return the new territory id, -1 if insert fails
	 */
	public static long createTerritory(DbAdapter db, int number, String town) {
		long id = db.insertTerritory(number, town);
		return id;
	}

	public static Territory getTerritoryById(DbAdapter db, long id) {
		Territory result = null;
		ContentValues val = db.selectById(DbAdapter.TABLE_TERRITORY, id);
		result = new Territory(id, val.getAsInteger(
				TerritoryColumns.NUMBER).intValue(), val
				.getAsString(TerritoryColumns.TOWN));
		return result;
	}

	public static Territory getTerritoryByNumber(DbAdapter db, int number) {
		Territory result = null;
		ContentValues val = db.selectByName(DbAdapter.TABLE_TERRITORY,
				TerritoryColumns.NUMBER, String.valueOf(number));
		result = new Territory(val.getAsLong(BaseColumns._ID), number, val
				.getAsString(TerritoryColumns.TOWN));
		return result;
	}

	public static List<Territory> getTerritoryList(DbAdapter db) {
		List<Territory> result = new ArrayList<Territory>();
		Territory temp = null;
		Cursor c = db.selectTable(DbAdapter.TABLE_TERRITORY,null,TerritoryColumns.NUMBER);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			temp = new Territory(c.getLong(c
					.getColumnIndex(BaseColumns._ID)), c.getInt(c
					.getColumnIndex(TerritoryColumns.NUMBER)), c
					.getString(c.getColumnIndex(TerritoryColumns.TOWN)));
			result.add(temp);
			c.moveToNext();
		}
		return result;
	}
}
